#!/bin/sh

usage () {
	cat <<EOF>&2
Usage: ${0##*/}

Snapshot all Btrfs subvolumes older than 10 minutes to a read-only '.snapshots/SUBVOLUME/DATE'.

Options:

  -n: No preview.
  -g: Run "git gc" on all .git folders.

EOF
}

OPT_PREVIEW=true
OPT_GIT_GC=false
while getopts ":ghn" opt; do
	case $opt in
	g)
		OPT_GIT_GC=true ;;
	h)
		usage
		exit ;;
	n)
		OPT_PREVIEW=false ;;
	\?)
		usage
		exit 1 ;;
	esac
done

shift $(($OPTIND - 1))

git_gc() { # $1=rootdir
	find "$1" -type d -name ".git" -print -exec git --git-dir {} gc \;
}

snap () { # $1=fs $2=subvol
	local fs=$1
	local subvol=$2

	local choice=N
	local last=$(find "$fs/.snapshots/$subvol" -maxdepth 1 | tail -1)

	$OPT_GIT_GC && git_gc "$fs/subvol"
	$OPT_PREVIEW && rmirror -i "$fs/$subvol" "$last"

	echo -n "==> Snapshot '$fs/${subvol}'? (y/N) "
	read -r choice
	echo ""
	case "$choice" in
	Y|y)
		btrfs-snap "$fs/$subvol" ;;
	esac
}

for fs in $(findmnt -l -t btrfs -n --output TARGET | grep /media); do
	for subvol in private public; do
		last=$(ls -1 "$fs"/.snapshots/"$subvol" | tail -1 | sed 's/_/ /')
		if [ -z "$last" ]; then
			continue
		fi
		last_date=$(date --date="$last" +%s)
		now=$(date +%s)
		if [ $(($now - $last_date)) -gt 600 ]; then
			snap "$fs" "$subvol"
		fi
		unset now
		unset last_date
		unset last
	done
done
